package com.songxh.core.base;

import com.songxh.core.exception.BizException;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

/**
 * 自定义结果返回包装类
 * @author songxh
 * @create 2022-12-19-11:21
 */
@NoArgsConstructor
public class CommonResult<T> {

    private Integer code = 200;
    private boolean success = true;
    private String message;
    private T data;

    public CommonResult(Integer code, String message) {
        this(code, message, null);
    }

    public CommonResult(Integer code, String message, T o) {
        this.code = code;
        this.message = message;
        this.data = o;
    }

    public CommonResult(String message, T o) {
        this.message = message;
        this.data = o;
    }

    public static CommonResult success() {
        CommonResult result = new CommonResult(HttpStatus.OK.value(), "操作成功");
        return result;
    }

    public static <T> CommonResult<T> success(T o) {
        CommonResult result = new CommonResult(HttpStatus.OK.value(), "操作成功");
        result.setData(o);
        return result;
    }

    public static <T> CommonResult<T> success(T o, String message) {
        CommonResult result = new CommonResult(HttpStatus.OK.value(), message);
        result.setData(o);
        return result;
    }

    public static CommonResult failure(String errorMsg) {
        CommonResult result = new CommonResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMsg, Boolean.FALSE);
        result.setSuccess(false);
        return result;
    }

    public static <T> CommonResult<T> failure(T o, String errorMsg) {
        CommonResult result = new CommonResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMsg, Boolean.FALSE);
        result.setData(o);
        result.setSuccess(false);
        return result;
    }


    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    /**
     * 检查返回值正确性
     *
     * @param tipHead
     */
    public void checkNoneNull(String tipHead) {
        String tip = StringUtils.isEmpty(tipHead) ? "" : tipHead + ": ";
        if (!isSuccess()) {
            throw new BizException(tip + this.message);
        }
        if (null == data) {
            throw new BizException(tipHead);
        }
    }

}
